package org.example.Server.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;

import java.io.IOException;
import java.net.URLEncoder;

public class BanWordsUtil {

    private static final String clientSecret = "suEdgrNUhgdkW8om84084d4zix8uehEr";
    private static final String clientId = "n27DdwGsbmimAzlvmVNBUPiU";
    private static final String accessToken = "24.117e20a94c9b38c0ecdf4376e9683d99.2592000.1748965089.282335-118351867";
    public static final String ERROR_WORD = "2";
    public static final String RIGHT_WORD = "1";


    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    public static String TextCensor(String text) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");
            RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), param);
            Request request = new Request.Builder()
                    .url(url + "?access_token=" + accessToken)
                    .post(body)
                    .build();

            try (Response response = HTTP_CLIENT.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    return getRepString(response.body().string(), "conclusionType");
                } else {
                    System.err.println("请求失败，响应码: " + response.code());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=client_credentials")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
//        System.out.println(response.body().string());
        String accesstoken = response.body().string();
        return getRepString(accesstoken, "access_token");

    }

    private static String getRepString(String jsonResponse, String key) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonResponse);
        return rootNode.get(key).asText();
    }
}
